package com.kbatis.sqlsession;

import com.kbatis.executor.SimpleExecutor;
import com.kbatis.executor.iface.Executor;
import com.kbatis.executor.CacheExecutor;
import com.kbatis.config.Configuration;
import com.kbatis.config.MappedStatement;

import java.util.List;



/**
 * @ClassName DefaultSqlSession
 * @Description
 * @Author 小黄
 * @Date 2019/11/15 20:01
 * @Version 1.0
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <T> T selectOne(String statementId, Object param, Boolean isHightLight) {
        List<Object> list = this.selectList(statementId, param, isHightLight);
        if (list != null && list.size() == 1) {
            return (T)list.get(0);
        }
        return null;
    }

    @Override
    public <T> List<T> selectList(String statementId, Object param, Boolean isHightLight) {
        MappedStatement mappedStatementById = configuration.getMappedStatementById(statementId);
        Executor executor = new CacheExecutor(new SimpleExecutor());
        return executor.queryList(mappedStatementById,configuration,param, isHightLight);
    }

    @Override
    public Long getCount(String statementId, Object param) {
        MappedStatement mappedStatementById = configuration.getMappedStatementById(statementId);
        Executor executor = new CacheExecutor(new SimpleExecutor());
        return executor.queryRecordNumber(mappedStatementById, configuration, param);
    }

    @Override
    public Boolean executeInsert(String statementId, Object param) {
        return execute(statementId, param);
    }

    @Override
    public Boolean executeDelete(String statementId, Object param) {
        return execute(statementId, param);
    }

    @Override
    public Boolean executeUpdate(String statementId, Object param) {
        return execute(statementId, param);
    }

    private Boolean execute(String statementId, Object param) {
        MappedStatement mappedStatementById = configuration.getMappedStatementById(statementId);
        Executor executor = new CacheExecutor(new SimpleExecutor());
        return executor.execute(mappedStatementById, configuration, param);
    }
}
